import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useRef } from "react";
import { DataGrid, Column, Toolbar, Item, } from "devextreme-react/data-grid";
import { CpasIcon, DevPopup } from "~/public/cpas-ui";
import DraftApi from "./DraftApi";
import Notify from "devextreme/ui/notify";
import { Popup, ToolbarItem } from "devextreme-react/popup";
import Form, { Item as FormItem } from "devextreme-react/form";
import { Modal, Progress } from "antd";
import "./_style.less";
import CloudTemplatePopup from "../../components-bs/components/TemplatePopup/CloudTemplatePopup";
import { nanoid10 } from "../../tools/Tools";
const CpasDataGrid = DataGrid;
const CpasColumn = Column;
const CpasToolbar = Toolbar;
const CpasItem = Item;
const CpasPopup = Popup;
const CpasForm = Form;
export const DraftManage = (props) => {
    const [gridData, setGridData] = useState([]);
    const [currentRows, setCurrentRow] = useState();
    const [isLoading, setIsLoading] = useState(false);
    const [isConfirm, setConfirm] = useState(false);
    const [isRename, setIsRename] = useState(false);
    const [rename, setRename] = useState({
        name: "",
    });
    let importInterval = null;
    let exportInterval = null;
    const [processObj, setProcess] = useState({
        process: 0,
        message: "准备开始",
    });
    const Form = useRef();
    const Grid = useRef();
    const popupRef = useRef();
    const currentRow = useRef();
    // 云端下载
    const CloudPopupRef = useRef();
    function Toast(msg, type) {
        if (!type) {
            type = "info";
        }
        Notify({
            message: `${msg}`,
            height: 45,
            width: 300,
            minWidth: 150,
            displayTime: 3500,
            type: type,
            position: "top center",
            animation: {
                show: {
                    type: "fade",
                    duration: 400,
                    from: 0,
                    to: 1,
                },
                hide: { type: "fade", duration: 40, to: 0 },
            },
        });
    }
    async function getMbTypeData() {
        const mbTypeData = await DraftApi.mbType();
        setGridData([...mbTypeData]);
    }
    useEffect(() => {
        getMbTypeData();
    }, []);
    function selectRow(e) {
        const select_data = e.data;
        currentRow.current = select_data;
        setCurrentRow(select_data);
    }
    async function exportDraft() {
        console.log(currentRow.current, "currentRow.current----");
        if (!currentRow.current) {
            Toast("请选择要导出的底稿", "error");
            return;
        }
        const name = currentRow.current["MBMC"];
        let electronComponents;
        if (window.parent) {
            electronComponents = window.parent["electronComponents"];
        }
        else {
            electronComponents = window["electronComponents"];
        }
        const dialog_result = await electronComponents["openDirectoryDialog"]();
        console.log(dialog_result);
        if (dialog_result.canceled === true) {
            return;
        }
        else {
            const checkFolderPath = dialog_result["filePaths"][0];
            startExportStatus();
            setIsLoading(true);
            const mbTypeData = await DraftApi.export(name, checkFolderPath);
            setProcess({
                process: 100,
                message: "完成",
            });
            setIsLoading(false);
            stopExportStatus();
            if (mbTypeData["code"] === 200) {
                Toast("导出成功", "success");
            }
            else {
                Toast(mbTypeData["msg"], "error");
            }
        }
    }
    async function importDraft() {
        let electronComponents;
        if (window.parent) {
            electronComponents = window.parent["electronComponents"];
        }
        else {
            electronComponents = window["electronComponents"];
        }
        const dialog_result = await electronComponents["openFileDialog"]("rar");
        console.log(dialog_result, "-------dialog_result");
        if (dialog_result.canceled === true) {
            return;
        }
        else {
            const checkFilePath = dialog_result["filePaths"][0];
            const path = checkFilePath;
            const fileName = path.substring(path.lastIndexOf("\\") + 1);
            const r = await DraftApi.isExits(fileName);
            if (r.msg === "yes") {
                // 导入判断-----
                popupRef.current.show({
                    title: "提示",
                    okCallback: async () => {
                        setIsLoading(true);
                        setProcess({
                            process: 0,
                            message: "准备开始",
                        });
                        startImportStatus();
                        const mbTypeData = await DraftApi.import(checkFilePath);
                        setProcess({
                            process: 100,
                            message: "完成",
                        });
                        stopImportStatus();
                        setIsLoading(false);
                        if (mbTypeData["code"] === 200) {
                            Toast("导入成功", "success");
                            getMbTypeData();
                        }
                        else {
                            Toast(mbTypeData["msg"], "error");
                        }
                    },
                });
            }
            else {
                setIsLoading(true);
                startImportStatus();
                const mbTypeData = await DraftApi.import(checkFilePath);
                setProcess({
                    process: 100,
                    message: "完成",
                });
                setIsLoading(false);
                stopImportStatus();
                if (mbTypeData["code"] === 200) {
                    Toast("导入成功", "success");
                    getMbTypeData();
                }
                else {
                    Toast(mbTypeData["msg"], "error");
                }
            }
        }
    }
    function startImportStatus() {
        importInterval = setInterval(async () => {
            const result = await DraftApi.getImportState();
            setProcess(result);
        }, 300);
    }
    function stopImportStatus() {
        setProcess({
            process: 0,
            message: "准备开始",
        });
        clearInterval(importInterval);
    }
    function startExportStatus() {
        exportInterval = setInterval(async () => {
            const result = await DraftApi.getExportState();
            setProcess(result);
        }, 300);
    }
    function stopExportStatus() {
        clearInterval(exportInterval);
        setProcess({
            process: 0,
            message: "准备开始",
        });
    }
    async function refresh() {
        await getMbTypeData();
    }
    async function removeDraft(type) {
        console.log(currentRows, "currentRows---");
        setConfirm(false);
        if (type === "ok" && currentRows) {
            const name = currentRows["MBMC"];
            setIsLoading(true);
            const mbTypeData = await DraftApi.remove(name);
            setIsLoading(false);
            if (mbTypeData["code"] === 200) {
                Toast("删除成功", "success");
                refresh();
            }
            else {
                Toast(mbTypeData["msg"], "error");
            }
        }
    }
    function renameConfirm(data) {
        setCurrentRow(data);
        if (!data) {
            Toast("请选择要重命名的底稿", "error");
            return;
        }
        const name = data["MBMC"];
        setRename({
            name: name,
        });
        setIsRename(true);
    }
    async function removeConfirm(data) {
        setCurrentRow(data);
        if (!data) {
            Toast("请选择要删除的底稿", "error");
            return;
        }
        setConfirm(true);
    }
    async function DraftRename(type) {
        if (type === "ok") {
            if (Form.current && currentRows) {
                const name = currentRows["MBMC"];
                //如果名称相等则直接返回
                if (name === rename.name) {
                    setIsRename(false);
                    Toast("重命名成功", "success");
                    return;
                }
                const devForm = Form.current;
                const result = await devForm.instance.validate().complete;
                if (result.isValid === true && result.status === "valid") {
                    setIsLoading(true);
                    const result = await DraftApi.reName(name, rename.name);
                    await refresh();
                    setIsLoading(false);
                    if (result.msg === "success") {
                        Toast("重命名成功", "success");
                        // if (Grid.current) {
                        //   const devInstance = (Grid.current as DataGrid).instance;
                        //   const rowData = devInstance.getSelectedRowsData()[0];
                        //   console.log(rowData, "rowData---");
                        //   rowData.MBMC = rename.name;
                        //   currentRow.current = rowData;
                        //   setCurrentRow(rowData);
                        //   // setRename({ name: rowData.name });
                        // }
                    }
                    else {
                        Toast(result["msg"], "error");
                    }
                    setIsRename(false);
                }
            }
        }
        else {
            setIsRename(false);
        }
    }
    const validationRules = {
        name: [
            { type: "required", message: "请填写底稿名称" },
            {
                type: "async",
                message: "底稿名称已存在",
                validationCallback: async (item) => {
                    const result = await DraftApi.isExits(item.value);
                    if (result["msg"] === "yes") {
                        return false;
                    }
                    return true;
                },
            },
        ],
    };
    const validateForm = (e) => {
        console.log("e.component");
        console.log(e.component);
        const result = e.component.validate();
        if (result === true) {
        }
        else {
        }
    };
    const Columns = [
        {
            dataField: "MBMC",
            caption: "底稿模板名称",
            alignment: "left",
        },
        {
            dataField: "count",
            caption: "底稿数量",
            alignment: "right",
            width: 90,
        },
        {
            caption: "操作",
            alignment: "center",
            width: 150,
            cellRender: (cell) => {
                console.log(cell.data, "-----");
                return (_jsx("span", { children: "1111" })
                // <div
                //   style={{
                //     display: "flex",
                //     alignContent: "center",
                //     justifyContent: "center",
                //   }}
                // >
                //   {/* <div className="Icon_Style"> */}
                //   <CpasIcon
                //     type={"icon-rename-copy"}
                //     onClick={() => {
                //       renameConfirm(cell.data);
                //     }}
                //   />
                //   {/* </div> */}
                //   {/* <div className="Icon_Style"> */}
                //   <CpasIcon
                //     type={"icon-delete"}
                //     onClick={() => {
                //       removeConfirm(cell.data);
                //     }}
                //   />
                //   {/* </div> */}
                // </div>
                );
            },
        },
    ];
    return (_jsxs("div", { className: "cpas-draft-manage fixContent", children: [_jsxs(Modal, { visible: isLoading, closable: false, maskStyle: {
                    backgroundColor: "transparent",
                }, footer: null, children: [isLoading && (_jsx(Progress, { percent: processObj.process }, nanoid10())), _jsx("div", { style: { paddingTop: 10 }, children: processObj.message })] }), _jsxs(CpasPopup, { visible: isRename, dragEnabled: true, showCloseButton: true, showTitle: true, onHiding: () => {
                    setIsRename(false);
                }, title: "\u5E95\u7A3F\u91CD\u547D\u540D", width: 450, height: 200, children: [_jsx(ToolbarItem, { widget: "dxButton", toolbar: "bottom", location: "after", options: {
                            text: "取消",
                            onClick: () => {
                                DraftRename("cancel");
                            },
                        } }), _jsx(ToolbarItem, { widget: "dxButton", toolbar: "bottom", location: "after", options: {
                            text: "确认",
                            type: "default",
                            onClick: () => {
                                DraftRename("ok");
                            },
                        } }), _jsx(CpasForm, { onFieldDataChanged: validateForm, ref: Form, focusStateEnabled: true, labelMode: "outside", formData: rename, readOnly: false, showColonAfterLabel: true, labelLocation: "left", width: 410, colCount: 1, children: _jsx(FormItem, { dataField: "name", label: {
                                text: "底稿名称",
                            }, validationRules: validationRules.name }) })] }), _jsxs(CpasPopup, { visible: isConfirm, dragEnabled: true, showCloseButton: true, showTitle: true, onHiding: () => {
                    setConfirm(false);
                }, title: "\u63D0\u793A", width: 450, height: 180, children: [_jsx(ToolbarItem, { widget: "dxButton", toolbar: "bottom", location: "after", options: {
                            text: "取消",
                            onClick: () => {
                                removeDraft("cancel");
                            },
                        } }), _jsx(ToolbarItem, { widget: "dxButton", toolbar: "bottom", location: "after", options: {
                            text: "确认",
                            type: "default",
                            onClick: () => {
                                removeDraft("ok");
                            },
                        } }), _jsxs("p", { children: ["\u60A8\u786E\u8BA4\u8981\u5220\u9664", " ", _jsxs("span", { style: { color: "red" }, children: ["'", currentRows ? currentRows["MBMC"] : "未获取到底稿名称", "'", " "] }), "\u5E95\u7A3F\u5417?"] })] }), _jsxs(DataGrid, { className: "PaperDevSortableGrid", dataSource: gridData, ref: Grid, keyExpr: "MBCode", focusedRowEnabled: true, hoverStateEnabled: true, allowColumnResizing: true, showColumnLines: true, showBorders: true, showRowLines: true, allowColumnReordering: true, 
                // onSelectionChanged={selectRow}
                onCellClick: selectRow, searchPanel: {
                    visible: true,
                    placeholder: "",
                }, toolbar: {
                    items: [
                        {
                            location: "before",
                            text: "底稿模板",
                        },
                        {
                            location: "after",
                            widget: "dxButton",
                            options: {
                                type: "default",
                                icon: "iconfont icon-icon-zaixianxiangmuliebiao",
                                text: "云端下载",
                                onClick: () => {
                                    CloudPopupRef.current.showTemplate();
                                },
                            },
                        },
                        {
                            location: "after",
                            widget: "dxButton",
                            options: {
                                width: "88px",
                                text: "导入",
                                onClick: () => importDraft(),
                            },
                        },
                        {
                            location: "after",
                            widget: "dxButton",
                            options: {
                                width: "88px",
                                text: "导出",
                                onClick: () => exportDraft(),
                            },
                        },
                        {
                            name: "searchPanel",
                            location: "after",
                            options: {
                                width: "120px",
                                visible: true,
                            },
                        },
                        {
                            location: "after",
                            widget: "dxButton",
                            cssClass: "refresh_Style",
                            options: {
                                icon: "iconfont icon-refresh",
                                onClick: () => refresh(),
                            },
                        },
                    ],
                }, 
                // columnResizingMode="widget"
                columnMinWidth: 100, children: [_jsx(Column, { dataField: "MBMC", caption: "\u5E95\u7A3F\u6A21\u677F\u540D\u79F0", alignment: "left" }), _jsx(Column, { dataField: "count", caption: "\u5E95\u7A3F\u6570\u91CF", alignment: "right", width: 90 }), _jsx(Column, { dataField: "MBMC", caption: "\u64CD\u4F5C", alignment: "center", width: 110, cellRender: (cell) => {
                            // console.log(cell.data, "cell.data---");
                            // currentRow.current = cell.data;
                            return (_jsxs("div", { style: {
                                    display: "flex",
                                    alignContent: "center",
                                    justifyContent: "center",
                                }, children: [_jsx("div", { className: "Icon_Style", children: _jsx(CpasIcon, { type: "icon-rename-copy", onClick: () => {
                                                renameConfirm(cell.data);
                                            } }) }), _jsx("div", { className: "Icon_Style", children: _jsx(CpasIcon, { type: "icon-delete", onClick: () => {
                                                removeConfirm(cell.data);
                                            } }) })] }));
                        } })] }), _jsx(DevPopup.Default, { ref: popupRef, children: () => {
                    return _jsx("span", { children: "\u8BE5\u6A21\u677F\u5DF2\u7ECF\u5B58\u5728,\u786E\u5B9A\u8986\u76D6\u8BE5\u6A21\u677F\u5417\uFF1F" });
                } }), _jsx(CloudTemplatePopup, { ref: CloudPopupRef, cloudData: {
                    cloudTempType: "底稿模板",
                }, reloadTable: () => {
                    getMbTypeData();
                } })] }));
};
export default DraftManage;
